<template>
  <setting-public-view current="cardManage" view-class="setting-view-main2" :nav="taskNav">
    <div id="task-additional-guide"></div>
    <div class="task-tab-header">
      <div class="task-tabs">
        <el-tabs v-model="activeTab" @tab-click="switchTab" id="task-additional-tabs-guide">
          <el-tab-pane name="task-added" :label="$t('event.setting.additional.label1')">
            <div class="tabs_msg">{{$t('task.tip.taskAdditionalTip2')}}</div>
          </el-tab-pane>
          <el-tab-pane name="task-import" :label="$t('event.setting.additional.label2')">
            <div class="tabs_msg">
              <i18n path="event.setting.additional.des2">
                <span place="data1">{{$t('common.base.preview')}}</span>
              </i18n>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="lh-52" v-if="activeTab=='task-added'">
        <el-button type="primary" :loading="false" @click="addTaskCard" v-track="$track.formatParams('CREATE_ADD_ONS')">
          <i class="iconfont icon-add2"></i>{{$t('common.base.create')}}
        </el-button>
      </div>
    </div>

    <div class="task-type-list" v-loading="loading" v-show="activeTab=='task-added'" :class="activeTab=='task-import' && 'task-type-template'">
      <div class="task-type-list-content">
        <!-- start 已添加附加组件 -->
        <task-card-item
          class="task-type-item"
          v-for="(item, idx) in cardList"
          :key="item.id"
          :card.sync="cardList[idx]"
          @update="updateCardname"
      ></task-card-item>
        <!-- end 已添加附加组件 -->
      </div>
    </div>

    <div class="task-type-list task-type-template" v-loading="loading" v-show="activeTab=='task-import'">
      <!-- start 从模版库添加 -->
      <template-library 
        :card-sys-list="cardSysList" 
        :card-group="cardGroup" 
        @update="updateCardTemplate" 
      >
      </template-library>
      <!-- end 从模版库添加 -->
    </div>

    <!-- start 无数据 -->
    <no-data-view-new 
      v-if="isShowNoData" 
      :notice-msg="$t('event.setting.serviceEventTypeSetting.flow.steps.cardSettingPanel.tips4')"
    ></no-data-view-new> 
    <!-- end 无数据 -->
      
    <!-- 创建附加组件 -->
    <edit-cardname-dialog ref="batchCardnameDialog"></edit-cardname-dialog>
  </setting-public-view>
</template>

<script>
// api
import * as SettingTaskApi from '@src/api/SettingTaskApi';
// util
import _ from 'lodash';
import { isShowCardWorkTime, isStandardEdition, isExperienceEdition, isBasicEditionHideSystemCard } from '@shb-lib/version'
// components
import TaskNavBar from '../../components/TaskNavBar';
import TaskCardItem from './components/TaskCardItem';
import EditCardnameDialog from './components/EditCardnameDialog';
import templateLibrary from './components/templateLibrary';
import NoDataViewNew from '@src/component/common/NoDataViewNew';
import SettingPublicView from '../../../components/settingPublicView';

// 新存储工具方法
import { storageGet, storageSet } from '@src/util/storage.ts';
/* enum */
import StorageModuleEnum from '@model/enum/StorageModuleEnum';
/* 工单设置导航 */
import {taskNav} from '../../../components/settingPublicView/navList.js';

import { TASK_CARD_SETTING_GUIDE } from '@src/component/guide/taskSettingStore';

/* mixin */
import { VersionControlTaskMixin } from '@src/mixins/versionControlMixin'
import { getRootWindow } from '@src/util/dom';

export default {
  name: 'task-manage',
  mixins: [VersionControlTaskMixin],
  data() {
    return {
      loading: true,
      activeTab: 'task-added',
      cardList: [],
      cardGroup:{},

      cardSysList:[],
      taskNav:taskNav || {}
    };
  },
  computed: {
    isShowCardWorkTime() {
      return this._isShowCardWorkTime
    },
    isShowNoData() {
      return (this.activeTab == 'task-added' && this.cardList.length == 0) ;
    },
    // 基础版功能是否显示
    isBasicEditionHideSystemCard() {
      return isBasicEditionHideSystemCard() 
    },
    // 故障库
    isShowFaultLibrary() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.NEW_FAULT_LIBRARY || false
    },
  },
  mounted() {
    this.initCard();
    this.initCardSysList();

    // this.$nextTick(async() => {
    //   const guideStore = await storageGet(TASK_CARD_SETTING_GUIDE, 0, StorageModuleEnum.Task);
    //   if (guideStore > 0) return this.$Guide().destroy('task-additional-guide');

    //   this.$Guide([{
    //     id: 'task-additional-guide',
    //     content: '在此显示已经创建的附件组件',
    //     haveStep: true,
    //     nowStep: 1,
    //     domObj: () => {
    //       return document.getElementById('task-additional-tabs-guide').getElementsByClassName('el-tabs__item')[0]
    //     },
    //     lastFinish: true
    //   }, {
    //     id: 'task-additional-guide',
    //     content: '可以在模板库中选择系统已经定义好的附加组件，快速创建。',
    //     haveStep: true,
    //     nowStep: 2,
    //     domObj: () => {
    //       return document.getElementById('task-additional-tabs-guide').getElementsByClassName('el-tabs__item')[1]
    //     },
    //     lastFinish: true
    //   }], 0, '', (e) => {
    //     return new Promise((resolve, reject) => {
    //       resolve()
    //     })
    //   }).create()
    //     .then(res_ => {
    //       if(res_) storageSet(TASK_CARD_SETTING_GUIDE, '2', StorageModuleEnum.Task);
    //     })
    // })
  },
  methods: {
    switchTab(tab){
      if(this.activeTab == tab) return;
      if(this.activeTab == 'task-added'){
        this.initCard();
      }
      if(this.activeTab == 'task-import'){
        this.initCardSysList()
      }
    },
    // 更新列表数据
    updateCardname() {
      this.initCard();
    },
    // 更新模版库列表
    updateCardTemplate(){
      this.initCardSysList()
    },
    // 新建组件
    addTaskCard(){
      this.$refs.batchCardnameDialog.openDialog();
    },
    // 获取附加组件列表
    initCard() {
      SettingTaskApi.getAllCardList().then(res=>{
        const { code, message, result = [] } = res;
        this.loading = false;
        
        const isSuccess = code == 0
        if (!isSuccess) {
          return this.$message.error(message)
        }
        
        let cardList = result.slice()
        // 标准基础版和体验版 过滤工时记录组件
        if (!this.isShowCardWorkTime) {
          cardList = cardList.filter(card => card?.specialfrom !== '工时记录')
        }

        // 基础版过滤工时记录、备件清单、服务清单模块
        if (this.isBasicEditionHideSystemCard) {
          cardList = cardList.filter(card => card?.specialfrom !== '工时记录' && card.specialfrom !== '备件清单' && card.specialfrom !== '服务清单')
        }
        
        if(!this.isShowFaultLibrary) {
          cardList = cardList.filter(card => card?.specialfrom !== '故障清单')
        }
        this.cardList = cardList
        
      }).catch(error=>{
        this.loading = false;
      })
    },
    
    /** 
    * @description 获取组件库列表
    * 1.工时记录灰度控制 isShowCardWorkTime true显示 false隐藏
    */
    initCardSysList() {
      SettingTaskApi.getCardSysList().then(res=>{
        const { code, message, result } = res;
        if(code == 0){
          let cardList = result || [];
          
          if(!this.isShowCardWorkTime) {
            cardList = cardList.filter(function(card) {
              return card.cardName !== '工时记录';
            })
          }        
          // 基础版过滤工时记录、备件清单、服务清单模块
          if (this.isBasicEditionHideSystemCard) {
            cardList = cardList.filter(card => card.cardName !== '工时记录' && card.cardName !== '备件清单' && card.cardName !== '服务清单')
          }
          
          if(!this.isShowFaultLibrary) {
            cardList = cardList.filter(card => card?.cardName !== '故障清单')
          }

          let cardAll = cardList.slice();
          this.cardGroup = this.groupBy(cardAll, 'type')
        }else{
          this.$message.error(message);
        }
      }).catch(error=>{
        console.log(error)
      })
    },
    groupBy(cardAll, type) { 
      let cardObj = cardAll.reduce(
        (acc, card) => {
          if (!acc[card[type]]) {
            acc[card[type]] = []
          }
          acc[card[type]].push(card)
          return acc
        }, {})
      return cardObj
    },
  },
  components: {
    [SettingPublicView.name]: SettingPublicView,
    [TaskCardItem.name]: TaskCardItem,
    [EditCardnameDialog.name]: EditCardnameDialog,
    [NoDataViewNew.name]: NoDataViewNew,
    [templateLibrary.name]: templateLibrary   
  },
};
</script>
<style lang="scss">
.task-tabs {
  // tabs标签页
  .el-tabs {
    height: 100%;
    display: flex;
    flex-direction: column;

    &__header {
      margin: 0;

      .el-tabs__item {
        padding: 0 24px !important;
        color: $text-color-regular;
        font-weight: normal;

        &.is-active {
          color: $color-primary;
        }
      }
    }
    &__nav-wrap {
      &:after {
        height: 0;
      }
    }

    &__content {
      flex: 1;
      overflow: auto;
    }
  }
}
</style>
<style lang="scss" scoped>
@import "./taskAdditionalSet.scss";
</style>
